#!/usr/bin/env python
# _*_coding:utf-8_*_

"""
@Time :    2019/9/4 22:14
@Author:  ThinHeader
@File: serializers.py
@Software: PyCharm
"""

from rest_framework import serializers

from common.tools.money_cast import FloatToIntField, transforms_int
from wehelp.models import KanjiaInfo, KanJiaUserMaster, KanJiaUserMem


class KanjiaInfoSerializer(serializers.ModelSerializer):
    """
    微砍价序列化类
    """

    price_original = FloatToIntField(
        error_messages={
            'invalid': u'原价应为数字',
        }
    )
    price_discount = FloatToIntField(
        error_messages={
            'invalid': u'底价应为数字',
        }
    )
    sub_price_min = FloatToIntField(
        error_messages={
            'invalid': u'最少减价应为数字',
        }
    )
    sub_price_max = FloatToIntField(
        error_messages={
            'invalid': u'最多减价应为数字',
        }
    )

    class Meta:
        model = KanjiaInfo
        fields = ('id', 'shop', 'title', 'start_time', 'end_time', 'price_original', 'price_discount', 'sub_price_min',
                  'sub_price_max', 'sub_time', 'top_image', 'qrcode4xcx', 'shelve', 'music', 'desc', 'status')
        read_only_fields = ('id', 'shelve')


class KanMasterSerializer(serializers.ModelSerializer):
    price_discount = serializers.CharField(max_length=1024, source='get_price_discount', read_only=True)
    # has_order = serializers.SerializerMethodField(read_only=True)

    # def get_has_order(self, obj):
    #     if obj.order:
    #         if obj.order.state in [Order.STATE_PAYED, Order.STATE_SEND, Order.STATE_COMPLETE]:
    #             return True
    #     return False

    class Meta:
        model = KanJiaUserMaster
        fields = (
            'id',
            'name',
            'phone',
            'real_price',
            'cash_time',
            'price_discount',
            'has_consume',
            # 'has_order',
            'last_mod_time'
        )
        read_only_fields = ('id', 'last_mod_time')

    def validate_phone(self, data):
        if data is None:
            raise serializers.ValidationError('手机号不能为空')
        # reg = r'^1[356789]\d{9}$'
        # rex = re.compile(reg)
        if not len(data) == 11:
            raise serializers.ValidationError('手机号码非法！手机号码须以1开始，长度为11位')
        return data


class KanMemSerializer(serializers.ModelSerializer):
    real_sub_price = serializers.CharField(max_length=1024, source='get_sub_price', read_only=True)

    class Meta:
        model = KanJiaUserMem
        fields = ('id', 'sub_price', 'real_sub_price')
        read_only_fields = ('id',)

    def validate_sub_price(self, data):
        return transforms_int(data, 1)

